<template>
  <HouseTop @search="searchHandler" @add="addHandler" />
  <HouseTable :table-data="tableData" :current-page="currentPage" :page-size="pageSize" :total="total"
    @size-change="onSizeChange" @current-change="onCurrentChange" @edit="editHandler" @delete="deleteHandler" />
  <HouseDai v-model="show" :edit-data="editData" @add="addHouseHandler" @edit="editHouseHandler" />
</template>
<script setup>
import HouseDai from '@/components/house/HouseDai.vue';
import HouseTable from '@/components/house/HouseTable.vue';
import HouseTop from '@/components/house/HouseTop.vue';
import { ref, reactive, watch } from 'vue';
import { getHouse, deleteHouse, addHouse, editHouse } from '@/api/userApi'
// 表格数据
const tableData = ref([])
// 当前页
const currentPage = ref(1)
// 一页几条数据
const pageSize = ref(5)
// 总数居
const total = ref(100)
// 控制对话框的显示隐藏
const show = ref(false)
// 新增/编辑
const editData = ref(null)
// 监听show的值
watch(show, () => {
  if (!show.value) {
    editData.value = null
  }
})
// 渲染房屋表格
init()
async function init(id = "") {
  const data = Object.assign({ pageCode: currentPage.value, pageSize: pageSize.value }, { id })
  const res = await getHouse(data)
  tableData.value = res.list
  total.value = res.total
}
// 搜索
function searchHandler(data) {
  init(data.id)
}
// 新增
function addHandler() {
  show.value = true
}
// 切换一页数据
function onSizeChange(size) {
  pageSize.value = size
  init()
}
// 切换当前页
function onCurrentChange(current) {
  currentPage.value = current
  init()
}
// 编辑
function editHandler(row) {
  show.value = true
  editData.value = row
}
// 删除
async function deleteHandler(row) {
  const res = await deleteHouse(row)
  if (res.code === 10000) init()
}
// 确认新增
async function addHouseHandler(data) {
  const res = await addHouse(data)
  console.log(res);
  if (res.code === 0) init()
}
// 确认编辑
async function editHouseHandler(data) {
  const res = await editHouse(data)
  if (res.code === 0) init()
}
</script>
<style scoped></style>
